package cn.jekun.shop.web.service;

import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import cn.jekun.component.base.exceptions.BusinessException;
import cn.jekun.component.base.utils.SqlUtis;
import cn.jekun.component.base.validator.annotation.Mobile;
import cn.jekun.component.core.Constants;
import cn.jekun.component.core.bean.gen.ErpOrders;
import cn.jekun.component.core.bean.gen.ErpTxnSeq;
import cn.jekun.component.core.bean.gen.RsUser;
import cn.jekun.component.core.service.ComponentCoreService;
import cn.jekun.component.core.service.gen.ErpOrdersService;
import cn.jekun.component.core.service.gen.ErpTxnSeqService;
import cn.jekun.component.pay.base.BasePay;
@Service(AlipayWapService.BEAN_NAME)
public class AlipayWapService extends ComponentCoreService{
	//记录日志信息
	private static Logger logger=Logger.getLogger(AlipayWapService.class);
	public static final String BEAN_NAME = "cn.jekun.shop.web.service.AlipayWapService";
	@Resource(name=ErpOrdersService.BEAN_NAME)
	ErpOrdersService orpOrdersService;	
	@Resource(name=ErpTxnSeqService.BEAN_NAME)
	ErpTxnSeqService erpTxnSeqService;
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public JSONObject genAlipayParams(
			@ErpOrders.AnnoOrderId String order,
			String clientIp,
			@RsUser.AnnoUserId String userId,
			@Mobile(message="手机号码格式不正确") String mobile){
		logger.info(" ********************* AlipayWapService pay Begin *********************");
		JSONObject jsonObject = new JSONObject();
		if (StringUtils.isBlank(order)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"订单号不能为空");
		}
		if (StringUtils.isBlank(clientIp)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"客户端IP不能为空");
		}
		
		Map txnseqTempMap = new HashMap();
		txnseqTempMap.put(ErpTxnSeq.COL_ORDER_ID, order);
		txnseqTempMap.put(ErpTxnSeq.COL_TXN_STATE, Constants.TXN_STATE.TXN_O0);
		txnseqTempMap.put(ErpTxnSeq.COL_DEL_FLAG, "0");
		SqlUtis.prepareSql(txnseqTempMap, 
				SqlUtis.getSQL(txnseqTempMap, "a."+ ErpTxnSeq.COL_ORDER_ID,Types.VARCHAR,SqlUtis.EQ),
				SqlUtis.getSQL(txnseqTempMap, "a."+ ErpTxnSeq.COL_TXN_STATE,Types.VARCHAR,SqlUtis.EQ),
				SqlUtis.getSQL(txnseqTempMap, "a."+ ErpTxnSeq.COL_DEL_FLAG,Types.VARCHAR,SqlUtis.EQ));
		ErpTxnSeq erptxnseq = erpTxnSeqService.one(txnseqTempMap);
		
		if(erptxnseq != null){
			String delFlag = "1";//标识已删除
			ErpTxnSeq tempTxn = new ErpTxnSeq();
			tempTxn.setTxnSeqId(erptxnseq.getTxnSeqId());
			tempTxn.setDelFlag(delFlag);
			Map updateMap = new HashMap();
			updateMap.put("erpTxnSeq", tempTxn);
			updateMap.put(ErpTxnSeq.COL_TXN_SEQ_ID, erptxnseq.getTxnSeqId());
			SqlUtis.prepareSql(updateMap,
					SqlUtis.getSQL(updateMap, "a."+ ErpTxnSeq.COL_TXN_SEQ_ID,Types.VARCHAR,SqlUtis.EQ));
			erpTxnSeqService.update(updateMap);
		}
		
		Map formMap = new HashMap();
		formMap.put(ErpOrders.COL_ORDER_ID, order);//1：根据order去数据库查询order_id=order的订单判断其是否存在
		SqlUtis.prepareSql(formMap,SqlUtis.getSQL(formMap, "a."+ ErpOrders.COL_ORDER_ID,Types.VARCHAR,SqlUtis.EQ));
		
		ErpOrders erpOrder = orpOrdersService.one(formMap);
		if(erpOrder == null){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"此订单不存在");
		}
		//2：判断订单的订单状态是否为待付款order_status_id=5
		if(!erpOrder.getOrderStatusId().equals("5")){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"此订单为非待付款状态,不允许支付");
		}
		//3:判断订单的付款请求时间是否为空
		if(erpOrder.getPayReqTime() != null){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"此订单已发送支付请求");
		}
		//4：判断订单的付款确认时间是否为空
		if(erpOrder.getPayTime() != null){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"此订单已经支付完成了");
		}
		String OrderAmount =""+((erpOrder.getTempOnlinePayAmount())); //订单金额，格式：元.角分""+(int) ((erpOrder.getTotalAmount())*100)
	
		BasePay alipaywap=BasePay.CreateNewWebPay("08", order, OrderAmount);
		alipaywap.SetPayInfo("clientIp", clientIp);
		
		jsonObject=alipaywap.GenerateForm();
		logger.info("AlipayWapService 报文生成结束  *********************");
		
		String returnId = this.saveTxnInfo(order,Constants.TRANS_TYPE.GO_PAY,Constants.ONLINE_PAYMENT.ALIPAY_WAP,Constants.MAINFRAME_TYPE.WAP_PAY,"","0","","",Constants.PAY_CHANNEL.PAY_WAP);
		logger.info("AlipayWapService 交易日志保存结束  *********************");
		if(returnId == null){
			return this.executeRerutnFail(jsonObject);
		}
		else{
			return this.executeRerutn(jsonObject);
		}
	}
	/**
	 * 保存交易流水信息
	 * @param orderId 订单编号
	 * @param transType 交易类型 00支付，01撤消（退款）
	 * @param payType 支付方式 01 翼支付，02银联支付
	 * @param mType 主机类型 ，主机类型 ，00－银联支付 ;01－翼支付；02－积分支付；03－前台主机;04－后台主机，05－APP，06－网站， 07－终端
	 * @param extTxnId 外部交易流水号
	 * @param txnState 交易状态
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public String saveTxnInfo(
			@ErpOrders.AnnoOrderId String orderId,
			@ErpTxnSeq.AnnoTxnType String transType,
			@ErpTxnSeq.AnnoPayType String payType,
			@ErpTxnSeq.AnnoTrnType String mType,
			@ErpTxnSeq.AnnoExtTxnSeqId String extTxnId,
			@ErpTxnSeq.AnnoTxnState String txnState,
			@ErpTxnSeq.AnnoResCode String resCode,
			@ErpTxnSeq.AnnoResDesc String resDesc,
			@ErpTxnSeq.AnnoPayChannelId String payChannel){
		
		//开始根据订单编号得到订单信息
		if(orderId==null ||orderId.isEmpty()){
			return "";
		}
		if(resCode==null){
			resCode="";
		}
		if(resDesc==null){
			resCode="";
		}
		Map formTxnMap = new HashMap();
		formTxnMap.put(ErpOrders.COL_ORDER_ID, orderId);
		SqlUtis.prepareSql(formTxnMap,
				SqlUtis.getSQL(formTxnMap, "a."
				+ ErpOrders.COL_ORDER_ID,Types.VARCHAR,SqlUtis.EQ));
		ErpOrders erpOrder = orpOrdersService.one(formTxnMap);
		
		Map tempMap = new HashMap();
		ErpTxnSeq txnSeq = new ErpTxnSeq();
		txnSeq.setTxnType(transType);//交易类型 00支付;01撤消(退款);02退货;03查询
		txnSeq.setPayType(payType);//支付方式:01翼支付02银联支付03web银联支付
		txnSeq.setTrnType(mType);//mType 主机类型 ，主机类型 ，00－银联支付 ;01－翼支付；02－积分支付；03－前台主机;04－后台主机，05－APP，06－网站， 07－终端
		txnSeq.setPayChannelId(payChannel);
		txnSeq.setOrderId(orderId);//订单号
		txnSeq.setTxnDtTm((new SimpleDateFormat("yyyyMMddHHmmss")).format(erpOrder.getCreateTime()));//订单日期时间
		txnSeq.setTxnAmt(String.valueOf((int) ((erpOrder.getTotalAmount())*100)));//订单金额
		txnSeq.setInTxnDt(new SimpleDateFormat("yyyyMMddHHmmss").format(erpOrder.getCreateTime()));//内部交易日期
		txnSeq.setExtTxnSeqId(extTxnId);//外部交易流水号，发起交易时为空
		txnSeq.setBonusValue(0.00);//积分数量
		txnSeq.setFeeAmt("0");//手续费
		txnSeq.setTxnState(txnState);//交易状态（发起支付请求）
		txnSeq.setResCode(resCode);
		txnSeq.setResDesc(resDesc);
		txnSeq.setCreateOper("system");
		txnSeq.setDelFlag("0");//记录有效标识：0：未删除；1：已删除
		tempMap.put("erpTxnSeq", txnSeq);
		return erpTxnSeqService.insert(tempMap).toString();
	}
}
